package com.alibaba.sample.kantiezi.web.admin.module.action;

import com.alibaba.biz.command.Command;
import com.alibaba.biz.command.CommandSupport;
import com.alibaba.biz.command.dispatcher.CommandDispatcher;
import com.alibaba.biz.command.result.Result;

import com.alibaba.sample.kantiezi.biz.admin.result.AddProductResultCode;
import com.alibaba.sample.kantiezi.dal.dataobject.Product;

import com.alibaba.service.form.Form;
import com.alibaba.service.form.FormService;
import com.alibaba.service.form.Group;
import com.alibaba.service.template.TemplateContext;
import com.alibaba.service.uribroker.URIBrokerService;

import com.alibaba.turbine.module.action.TemplateAction;
import com.alibaba.turbine.service.rundata.RunData;
import com.alibaba.turbine.service.uribroker.uri.TurbineURIBroker;

import com.alibaba.webx.WebxException;

import org.apache.commons.fileupload.FileItem;

import java.io.IOException;

public abstract class AddProductAction extends TemplateAction {
    protected abstract FormService getFormService();

    protected abstract CommandDispatcher getCommandDispatcher();

    protected abstract URIBrokerService getURIBrokerService();

    public void doAdd(RunData rundata, TemplateContext context)
            throws WebxException {
        Form form = getFormService().getForm(rundata);

        if (form.isValid()) {
            Product  product = new Product();
            Group    group   = form.getGroup("addProduct");
            FileItem picture = group.getField("picture").getFileItem();

            group.setProperties(product);

            Command command = new CommandSupport("addProduct", "add");

            command.getParameters().put("product", product);
            command.getParameters().put("picture", picture);
            command.getParameters()
                   .put("categoryId", rundata.getParameters().getString("categoryId"));

            Result result = getCommandDispatcher().execute(command);

            if (result.isSuccess()) {
                TurbineURIBroker broker = (TurbineURIBroker) getURIBrokerService()
                                                                 .getURIBroker("adminModule",
                                                                               rundata);

                try {
                    rundata.setRedirectLocation(broker.setTarget("categoryList.vm").render());
                } catch (IOException e) {
                    throw new WebxException(e);
                }
            } else {
                if (result.getResultCode() == AddProductResultCode.DUPLICATED_PRODUCT_ID) {
                    group.getField("productId").setMessage("duplicatedProductId");
                }
            }
        }
    }
}
